﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Dokan;
using System.Diagnostics.Contracts;

namespace WindowsVHDClientNode
{
    /// <summary>
    /// A variation on the sample drive, to simulate a drive that is failing
    /// </summary>
    public class FailingDrive : SampleDrive
    {
        /// <summary>
        /// Constructs a failing drive
        /// </summary>
        public FailingDrive(char driveLetter, String volumneLabel, DirectoryInfo realMountingPoint) : base(driveLetter, volumneLabel, realMountingPoint)
        {
            Contract.Requires(volumneLabel != null);
            Contract.Requires(realMountingPoint != null); 
            Contract.Requires(realMountingPoint.FullName.Length > 1);

            _maxReadLength = 32;
        }

        [ContractInvariantMethod]
        private void ObjectInvariant()
        {
            Contract.Invariant(r != null);
        }

        private Random r = new Random();

        /// <summary>
        /// Reads a file from the failing drive
        /// </summary>
        public override int ReadFile(String filename, Byte[] buffer, ref uint readBytes,
            long offset, DokanFileInfo info)
        {
            Contract.Requires(filename != null);
            Contract.Requires(info != null);
            Contract.Requires(offset >= 0);
            Contract.Requires(buffer != null);

            if (r.Next(0, 100) > 50)
            {
                System.Threading.Thread.Sleep(TimeSpan.FromMilliseconds(r.Next(1, 3000)));
            }
            return base.ReadFile(filename, buffer, ref readBytes, offset, info);
        }
    }
}
